<?php
namespace app\admin\controller;

use think\Exception;

class Category extends Common
{
    private $obj;
    public function _initialize()
    {
        parent::_initialize();
        $this->obj = model('Category');
    }

    public function index()
    {
        $param = input('param.');
        $this->assign('param', $param);
        $where = [];
        $where['delete'] = 0;
        $where['status'] = 1;
        if (input('?param.status') && input('param.status') > 0) {
            $where['status'] = input('param.status');
        }
        if (input('?param.delete') && input('param.delete') > 0) {
            $where['delete'] = input('param.delete');
        }
        if (input('?param.name') && !empty(input('param.name'))) {
            $where['name'] = ['like', '%' . input('param.name') . '%'];
        }
        $data = $this->obj->all($where);
        //echo $this->obj->getLastSql(); exit;
        $this->assign('data', $data);
        return view();
    }

    public function category_save() {
        $id = input('param.id', 0);
        if (request()->isPost()) {
            /**
             * 组装数据
             */
            $data['name'] = input('post.name', '');
            $data['status'] = input('post.status', 0);

            /**
             * 检查分类名是否存在
             */
            $where['id'] = $id > 0 ? ['neq', $id] : ['neq', 0];
            $where['name'] = $data['name'];
            $cate = $this->obj->get($where);
            if ($cate) {
                $this->error('分类名已存在');
            }

            /**
             * 保存数据
             */
            $where = $id > 0 ? ['id' => $id] : [];
            $rs = $this->obj->save($data, $where);

            if ($rs) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        } else{
            $data = [];
            if ($id > 0) {
                $data = $this->obj->get(['id' => $id]);
            }
            $this->assign('data', $data);
            return view();
        }
    }

    /**
     * 编辑分类状态
     */
    public function save_category_status() {
        try {
            $id = input('param.id', 0);
            $value = input('param.value', 0);
            if (!$id || !$value) {
                $this->error('参数错误!');
            }
            model('category')->save(['status' => $value], ['id' => $id]);
            $this->success('修改成功！');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 软删除分类
     */
    public function save_category_delete() {
        try {
            $id = input('param.id', 0);
            $value = input('param.value', 0);
            if (!$id || !$value) {
                $this->error('参数错误!');
            }
            model('category')->save(['delete' => $value], ['id' => $id]);
            $this->success('修改成功！');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}
